import 'dart:io';
import 'dart:math';

import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_app_info.dart';
import 'package:xindong/common/xindong_all.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/common/xindong_storage.dart';
import 'package:xindong/common/xindong_types.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/manager/xindong_user_controller.dart';
import 'package:xindong/routes/account/model/xindong_register_class.dart';
import 'package:xindong/utils/xindong_calender_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';

class XinDongRegisterCtr extends GetxController {
  static XinDongRegisterCtr get to => Get.find();
  XinDongRegisterClass registerClass = XinDongRegisterClass();

  File? avatarFile;

  // 获取错误次数
  int errorCount = 0;

  // 配置
  // 重置数据，避免下次使用同样的数据
  void setup() {
    avatarFile = null;
    errorCount = 0;
    registerClass = XinDongRegisterClass();
  }

  // 递归生成邀请渠道
  Future<String> generatorInviteCode() async {
    // 等待渠道信息抓取
    if (XinDongAll.instance.inviteCode == null) {
      if (errorCount++ < 2) {
        await Future.delayed(const Duration(seconds: 1));
        return generatorInviteCode();
      }
      XinDongAll.instance.inviteCode = "";
      XinDongStorage.instance.saveString(XinDongStorageKey.invite, XinDongAll.instance.inviteCode!);
    }
    // 邀请码代替邀请人
    if (!TextUtil.isEmpty(registerClass.send_code)) {
      XinDongAll.instance.inviteCode = registerClass.send_code;
    }
    errorCount = 0;
    return XinDongAll.instance.inviteCode!;
  }

  // 开始注册
  Future<void> startRegister() async {
    // 检测资料完善后即可通过注册
    if (checkEnableRegister(avatarFile) == false) {
      return;
    }
    // 开始请求
    showLoading();
    if (avatarFile != null) {
      final fileUrl = await XinDongNetworking.instance.uploadFile(filePath: avatarFile!.path);
      if (!TextUtil.isEmpty(fileUrl)) {
        mDebugPrint('返回图片结果$fileUrl');
        // 记录头像地址
        registerClass.head = fileUrl!;
      }
    }
    mDebugPrint(registerClass.toJson().toString());

    await _requestRegister();

    hideLoading();
  }

  // 请求注册
  Future<void> _requestRegister() async {
    // 设备码
    registerClass.oaid = XinDongAppDeviceInfo.instance.deviceOAID;
    registerClass.device_id = XinDongAppDeviceInfo.instance.deviceUDID;
    // 填充注册邀请信息
    String inviteCode = await generatorInviteCode();
    registerClass.send_code = inviteCode;
    // 参数
    var parameters = registerClass.toJson();
    final object = await XinDongNetworking.instance.request(
      XinDongApi.userRegister,
      method: XinDongHttpMethod.post,
      parameters: parameters,
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      XinDongUserController.to.commonLoginSuccessfulHandler(
        userId: object.id ?? "",
        sig: object.tencentId ?? "",
        gender: registerClass.sex,
      );
    }
    return Future.value();
  }
}

// 扩展 - 资料
extension AccountProfile on XinDongRegisterCtr {
  // 检测能否注册
  bool checkEnableRegister(File? avatarFile) {
    // 男的不需要上传头像
    // if (avatarFile == null && registerClass.gender == Gender.female) {
    //   showToast("请上传头像");
    //   return false;
    // }

    // 男女必填
    if (registerClass.name.isEmpty) {
      showToast("请输入昵称");
      return false;
    } else if (registerClass.name.length > 12) {
      showToast("昵称1～12字");
      return false;
    } else if (registerClass.sex == Gender.none) {
      showToast("请选择您的性别");
      return false;
    } else if (registerClass.birthday.isEmpty) {
      showToast("请选择您的生日");
      return false;
    }
    return true;
  }

  // 自动填充数据
  Future<void> autoFillData() async {
    // 头像
    if (registerClass.sex == Gender.male) {
      // 生日
      if (TextUtil.isEmpty(registerClass.birthday)) {
        int number = 22;
        if (registerClass.sex == Gender.male) {
          number = Random().nextInt(16) + 22;
        } else {
          number = Random().nextInt(11) + 18;
        }
        DateTime tempDate = XinDongCalendarUtil.yearsAgo(number);
        registerClass.birthday = XinDongCalendarUtil.dateFormatDateTime(tempDate, format: XinDongDateFormat.formatYMD);
      }
    }

    update();
    return Future.value();
  }
}
